package com.newjiabo.ski.task;

import cn.hutool.core.util.ObjectUtil;
import com.newjiabo.common.constant.CacheConstants;
import com.newjiabo.common.core.redis.RedisCache;
import com.newjiabo.common.utils.spring.SpringUtils;
import com.newjiabo.ski.domain.SkiOrder;
import com.newjiabo.ski.domain.enums.OrderStatusEnum;
import com.newjiabo.ski.service.ISkiOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * {类内容}
 *
 * @author CaoMengHui.
 * @version 1.0
 * @since 2023/10/12 15:05
 */
@Component
public class AutomaticReceiptService implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(AutomaticReceiptService.class);
    @Resource
    private RedisCache redisCache;
    @Resource
    private ISkiOrderService orderService;

    /**
     * 自动收货时间（天）
     */
    @Value("${order.automaticReceiptTime}")
    private long automaticReceiptTime;


    /**
     * 添加已支付的订单到延迟任务
     *
     * @param orderId
     */
    public void produce(String orderId) {
        redisCache.addZSetCache(CacheConstants.AUTOMATIC_RECEIPT_TASK_KEY,
                orderId,
                System.currentTimeMillis() + (60 * 60 * 24 * automaticReceiptTime * 1000)
        );
    }

    /**
     * 完成订单
     *
     * @param orderId
     * @return
     * @author CaoMengHui.
     * @date 2023/10/12 16:59
     */
    public void completeOrder(String orderId) {
        redisCache.removeZSet(CacheConstants.AUTOMATIC_RECEIPT_TASK_KEY, orderId);
    }

    @Async("automaticReceipt")
    public void consuming() {
        log.info("自动收货检索开始。。。");
        Set<ZSetOperations.TypedTuple<String>> orderSet = redisCache.getZSet(CacheConstants.AUTOMATIC_RECEIPT_TASK_KEY, 0, System.currentTimeMillis());
        if (ObjectUtil.isNotNull(orderSet)) {
            for (ZSetOperations.TypedTuple<String> orderId : orderSet) {
                String orderIdStr = orderId.getValue();
                log.info("订单id：{}，自动收货。", orderIdStr);
                // 更改订单状态
                orderService.updateStatusByOrderId(orderIdStr, OrderStatusEnum.completed);
                // 订单收货后，将订单从任务列表中剔除掉
                redisCache.removeZSet(CacheConstants.AUTOMATIC_RECEIPT_TASK_KEY, orderIdStr);
            }
        }
        log.info("自动收货检索结束。。。");
    }

    /**
     * 初始化订单信息：查询数据库中所有未收货的订单，
     */
    public void initOrder() {
        log.info("进入待收货订单初始化方法。。。开始。。。");
        SkiOrder order = new SkiOrder();
        order.setDelFlag(false);
        order.setOrderStatus(OrderStatusEnum.paid.name());
        List<SkiOrder> skiOrders = orderService.selectSkiOrderList(order);
        for (SkiOrder skiOrder : skiOrders) {
            redisCache.addZSetCache(CacheConstants.AUTOMATIC_RECEIPT_TASK_KEY, skiOrder.getOrderId(), skiOrder.getPayTime().getTime() + (60 * 60 * 24 * automaticReceiptTime * 1000));
        }
        log.info("进入待收货订单初始化方法。。。结束。。。");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initOrder();
        ScheduledExecutorService scheduledExecutorService = SpringUtils.getBean("scheduledExecutorService");
        scheduledExecutorService.schedule(new TimerTask() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    consuming();
                }
            }
        }, 10, TimeUnit.MILLISECONDS);
    }
}
